package com.digitalchina.lxnsy.activity.old;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.adapter.CropFirstAdapter;
import com.digitalchina.lxnsy.adapter.CropSecondAdapter;
import com.digitalchina.lxnsy.api.BusinessDataMall;
import com.digitalchina.lxnsy.api.BusinessRealTimePrice;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.base.BaseApplication;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.RealTimePriceVO;
import com.digitalchina.lxnsy.entity.SelectedCityVO;
import com.digitalchina.lxnsy.entity.TypeTempVO;
import com.digitalchina.lxnsy.service.LocationService;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.RealTimePriceHolder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.raizlabs.android.dbflow.sql.language.SQLite;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.City_Table;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.County_Table;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Province_Table;

import static com.digitalchina.lxnsy.activity.old.AddressSelectActivity.KEY_PICKED_CITY;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：改版的实时价格
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/1/22 15:20
 * 修改备注：去掉了market列表  并且分类重新定义
 * ================================================
 */
public class RealTimePriceActivityNew extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.data_mall_iv_menu)
    ImageView dataMallIvMenu; // 侧滑菜单按钮
    @Bind(R.id.data_mall_tv_search)
    TextView dataMallTvSearch; // 搜索按钮

    public static final int REQUEST_CODE_DATA_LIST = 10000;
    @Bind(R.id.real_time_price_drawerlayout)
    DrawerLayout drawerlayout;
    @Bind(R.id.listViewFirst)
    ListView listViewFirst;
    @Bind(R.id.listViewSecond)
    ListView listViewSecond;
//    @Bind(R.id.listViewMarket)
//    ListView listViewMarket;

    private LocationService locationService;
    private static final int BAIDU_FINE_LOCATION = 100;

    private int locateCount = 0;

    private RecyclerArrayAdapter adapter;
    private int page = 1;
    private int limit = 10;
    private String keyWord = "";

    private String marketCode = "";
    private String minTypeCode = "";

    //    private MarketAdapter marketAdapter;
    private CropFirstAdapter firstAdapter;
    private CropSecondAdapter secondAdapter;
//    private List<MarketVO> marketVOList = new ArrayList<>(); // 市场列表list

    private List<TypeTempVO> cropTypeVOList = new ArrayList<>(); // 农作物分类一级菜单
    private List<List<TypeTempVO.ListBean>> listList = new ArrayList<>(); // 二级菜单

    private List<RealTimePriceVO> realTimePriceVOList = new ArrayList<>();

    // 地址选择
    private String cityName = "";
    private SelectedCityVO cityVO = new SelectedCityVO();
    private BDLocation mLocation; // 定位信息
    private final int LOCATION_REQUEST_CODE = 129;

    // 标记是否获取成功
    private boolean getCropTypeList = false;

    private String provinceCode = "";
    private String cityCode = "";
    private String countyCode = "";

    private TextView textView;
    private List<TypeTempVO.ListBean> emptyList = new ArrayList<>(); // 二级菜单 空list


    @Override
    public void setLayout() {
        setTitle("实时价格");
        setContentLayout(R.layout.activity_real_time_price_list);
    }

    @Override
    protected void onStop() {
        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务
        super.onStop();
    }

    /*****
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(final BDLocation location) {
            locateCount = locateCount + 1;
            if (locateCount >= 10) { // 定位超过10次 停止定位
                locationService.stop();
            }
            if (null != location) {

                mLocation = location;
                if (location.getLocType() == BDLocation.TypeNetWorkLocation) { // 定位成功
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            cityName = location.getAddress().city;
                            dataMallTvSearch.setText(String.format("%s·%s", location.getCity(), location.getDistrict()));
                            if (null != location.getDistrict()) {
                                countyCode = getDistrictCodeWithName(location.getDistrict());
                                cityCode = getCityCodeWithName(location.getCity());
                                provinceCode = getProvinceCodeWithName(location.getProvince());
                                // 根据定位获取所有市场列表  省市区code 三级
//                                BusinessRealTimePrice.getMarketList(RealTimePriceActivityNew.this, "", "", districtCode, mHandler);
                            } else if (null != location.getCity()) {
                                cityCode = getCityCodeWithName(location.getCity());
                                provinceCode = getProvinceCodeWithName(location.getProvince());
                                // 根据定位获取所有市场列表  省市区code 三级
//                                BusinessRealTimePrice.getMarketList(RealTimePriceActivityNew.this, "", cityCode, "", mHandler);
                            }
                            onRefresh();
                        }
                    });
                    locationService.stop();

                } else if (location.getLocType() == BDLocation.TypeNetWorkException) { // 定位失败
                    showToast("定位失败，请检查网络是否通畅");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dataMallTvSearch.setText("定位失败");
                            // 根据定位获取所有市场列表  省市区code 三级
                            onRefresh();
//                            BusinessRealTimePrice.getMarketList(RealTimePriceActivityNew.this, "", "", "", mHandler);
                        }
                    });
                }
            }

        }

        public void onConnectHotSpotMessage(String s, int i) {
            LogUtils.e("onConnectHotSpotMessage s: " + s + "\ni: " + i);
        }
    };

    /**
     * @param provinceName 省
     * @return 市CODE
     */
    private String getProvinceCodeWithName(String provinceName) {
        Province province = SQLite.select()
                .from(Province.class)
                .where(Province_Table.province_name.eq(provinceName))
                .querySingle();
        if (province != null)
            return province.province_code;
        else
            return "";
    }

    /**
     * @param cityName 城市名
     * @return 市CODE
     */
    private String getCityCodeWithName(String cityName) {
        City city = SQLite.select()
                .from(City.class)
                .where(City_Table.city_name.eq(cityName))
                .querySingle();
        if (city != null)
            return city.city_code;
        else
            return "";
    }

    /**
     * 根据区/县名称获取区/县CODE
     *
     * @param districtName 区县名
     */
    private String getDistrictCodeWithName(String districtName) {
        County county = SQLite.select()
                .from(County.class)
                .where(County_Table.county_name.eq(districtName))
                .querySingle();
        if (county != null)
            return county.county_code;
        else
            return "";
    }

    @Override
    public void initMember() {
        getPermission();

        startLocation();

        initRecyclerView();

        getAssetsText();

        // 根据定位获取所有市场列表  省市区code 三级
//        BusinessRealTimePrice.getMarketList(this, "610000", "", "", mHandler);

        // 获取农作物类别和农作物二级菜单
//        BusinessPest.getCropTypeList(this, mHandler);
    }

    private void getAssetsText() {

        InputStream inputStream = null;
        try {
            inputStream = getAssets().open("typeJson.txt");
            int size = inputStream.available();
            int len = -1;
            byte[] bytes = new byte[size];
            inputStream.read(bytes);
            inputStream.close();
            String string = new String(bytes);
            setLeftView(string);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * BD 定位
     */
    private void startLocation() {
        // -----------location config ------------
        locationService = ((BaseApplication) getApplication()).locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        int type = getIntent().getIntExtra("from", 0);
        if (type == 0) {
            locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        } else if (type == 1) {
            locationService.setLocationOption(locationService.getOption());
        }
        locationService.start();
    }

    /**
     * 获取定位权限
     */
    @TargetApi(23)
    private void getPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{
                        Manifest.permission.ACCESS_FINE_LOCATION}, BAIDU_FINE_LOCATION);

            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == BAIDU_FINE_LOCATION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                showToast("获取权限成功");
            } else {
                // 没有获取到权限，做特殊处理
                showToast("手机定位未授权, 可能引起定位失败!");
            }
        }
    }

    private void initRecyclerView() {


        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.addItemDecoration(Utils.setSpaceDecoration(this, false, true, false));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new RealTimePriceHolder(parent);
            }
        });

//        onRefresh();
    }


    @Override
    public void addListener() {

        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                RealTimePriceVO realTimePriceVO = (RealTimePriceVO) adapter.getAllData().get(position);
                GotoUtil.gotoActivity(RealTimePriceActivityNew.this, RealTimePriceDetailsActivity.class, "RealTimePriceVO", realTimePriceVO);
            }
        });
        adapter.setOnItemLongClickListener(new RecyclerArrayAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(int position) {
                return true;
            }
        });

//        listViewMarket.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                marketCode = marketAdapter.getItem(position).getMarketCode();
//                marketAdapter.setSelectPosition(position);
//                marketAdapter.notifyDataSetChanged();
//                updataListView(0);
//            }
//        });

        listViewFirst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (position == 0) {
//                    isTypeData = false;
                    minTypeCode = "";
                    drawerlayout.closeDrawer(GravityCompat.START);
                    textView.setBackgroundResource(R.drawable.shape_real_time_type);
                    updateListView(-1);
                    onRefresh();
                } else {
                    textView.setBackgroundResource(R.drawable.shape_data_type_null);
                    updateListView(position - listViewFirst.getHeaderViewsCount());
                }

            }
        });

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);

                switch (msg.what) {
                    case MSG.MSG_GET_REAL_PRICE_LIST_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_REAL_PRICE_LIST_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                    case MSG.MSG_GET_MARKET_LIST_SUCCESS: // 市场列表
//                        setMarket(msg.obj.toString());
                        break;
                    case MSG.MSG_DATA_MART_LIST_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_GET_CROP_TYPE_LIST_SUCCESS: // 农作物分类
                        setLeftView(msg.obj.toString());
                        break;
                    case MSG.MSG_GET_CROP_TYPE_LIST_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    /**
     * 设置左侧市场列表
     *
     * @param s
     */
//    private void setMarket(String s) {
//        marketVOList = FastJsonUtil.getListBean(s, "body", "marketList", MarketVO.class);
//
//        if (marketVOList == null || marketVOList.size() == 0)
//            return;
//
//        marketAdapter = new MarketAdapter(this, marketVOList);
//
//        marketAdapter.setSelectPosition(0);
//        listViewMarket.setAdapter(marketAdapter);
//        marketCode = marketAdapter.getItem(0).getMarketCode();
//
//    }

    /**
     * 设置左侧农作物类型
     */
    private void setLeftView(String json) {
        cropTypeVOList = FastJsonUtil.getListBean(json, "body", "cropTypeList", TypeTempVO.class);

        if (cropTypeVOList == null || cropTypeVOList.size() == 0)
            return;

//        getCropTypeList = true;
        for (int i = 0; i < cropTypeVOList.size(); i++) {
            if (cropTypeVOList.get(i).getList() == null || cropTypeVOList.get(i).getList().size() == 0) {
                cropTypeVOList.remove(i);
                i--;
            } else

                listList.add(cropTypeVOList.get(i).getList());
        }

        firstAdapter = new CropFirstAdapter(this, cropTypeVOList);

        View view = LayoutInflater.from(RealTimePriceActivityNew.this).inflate(R.layout.item_mall_type, null);
        textView = (TextView) view.findViewById(R.id.item_tv_type);
        textView.setBackgroundResource(R.drawable.shape_real_time_type);
        textView.setText("全部分类");
        listViewFirst.addHeaderView(view);


        listViewFirst.setAdapter(firstAdapter);
        firstAdapter.setSelectPosition(-1);
        initSecondListView();
    }

    private void initSecondListView() {

        secondAdapter = new CropSecondAdapter(this, emptyList);
        listViewSecond.setAdapter(secondAdapter);

        listViewSecond.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                updateListView2(position, true);
            }
        });

    }


    private void updateListView(int position) {

        firstAdapter.setSelectPosition(position);
        firstAdapter.notifyDataSetChanged();

        if (position == -1) {
            secondAdapter.setDatas(emptyList);
            return;
        }

        //更新第二ListView
        secondAdapter.setDatas(listList.get(position));
        updateListView2(0, false);
    }

    private void updateListView2(int position, boolean b) {

        secondAdapter.setSelectPosition(position);
        secondAdapter.notifyDataSetChanged();


        if (b) {
            drawerlayout.closeDrawer(GravityCompat.START);
            minTypeCode = secondAdapter.getItem(position).getCode();
            onRefresh();
        }
    }

    @Override
    public void callBack(Object object) {

        realTimePriceVOList = FastJsonUtil.getListBean(object.toString(), "body", "produceList", RealTimePriceVO.class);
        if (page == 1) { // 刷新
            adapter.clear();
        }

        if (realTimePriceVOList != null) {
            if (realTimePriceVOList.size() < limit) {
                adapter.stopMore();
            }
        }

        adapter.addAll(realTimePriceVOList);
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public void onRefresh() {
        page = 1;
        marketCode = "";
        BusinessRealTimePrice.getRealPriceListNew(this, provinceCode, cityCode, countyCode, minTypeCode, String.valueOf(page), String.valueOf(limit), mHandler);
//        if (!getCropTypeList)
//            BusinessPest.getCropTypeList(this, mHandler);
    }

    @Override
    public void onLoadMore() {
            page++;
            BusinessRealTimePrice.getRealPriceListNew(this, provinceCode, cityCode, countyCode, minTypeCode, String.valueOf(page), String.valueOf(limit), mHandler);
    }

    @OnClick({R.id.data_mall_iv_menu, R.id.data_mall_tv_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.data_mall_iv_menu:
                drawerlayout.openDrawer(GravityCompat.START);
                break;
            case R.id.data_mall_tv_search:
                if (null == cityVO.getCityName() && null != mLocation) {
                    cityVO.setCityName(mLocation.getAddress().city);
                    cityVO.setCountyName(mLocation.getAddress().district);
                }
                GotoUtil.gotoForResultActivity(RealTimePriceActivityNew.this, AddressSelectActivity.class, LOCATION_REQUEST_CODE, "selectCityVO", cityVO);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == DataSearchActivity.RESULT_CODE_DATA_SEARCH) {
            if (null != data && requestCode == REQUEST_CODE_DATA_LIST) {
                //搜索返回数据
                if (null != keyWord || !"".equals(keyWord))
                    keyWord = "";
                if (null != adapter || adapter.getAllData().size() > 0) {
                    adapter.clear();
                    adapter.notifyDataSetChanged();
                }
                keyWord = data.getStringExtra("KeyWord");

                searchData(keyWord);
            }
        } else if (requestCode == LOCATION_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                Bundle bundle = data.getExtras();
                cityVO = (SelectedCityVO) bundle.get(KEY_PICKED_CITY);
                if (cityVO == null)
                    return;

                if (null != cityVO.getCountyCode() && null != cityVO.getCityName()) { // 含有区 显示 市区
                    dataMallTvSearch.setText(String.format("%s·%s", cityVO.getCityName(), cityVO.getCountyName()));
                    cityName = cityVO.getCityName();
                    if (!cityName.equals(cityVO.getCityName())) { // 切换了城市 刷新列表
                        // 根据定位获取所有市场列表  省市区code 三级
//                        BusinessRealTimePrice.getMarketList(RealTimePriceActivityNew.this, "", "", cityVO.getCountyCode(), mHandler);
                        cityCode = cityVO.getCityCode();
                        provinceCode = "";
                        countyCode = cityVO.getCountyCode();
                        marketCode = "";
                        minTypeCode = "";
                        onRefresh();
                    }
                } else { // 只含有 市 显示 市
                    dataMallTvSearch.setText(String.format("%s", cityVO.getCityName()));
                    cityName = cityVO.getCityName();
                    // 根据定位获取所有市场列表  省市区code 三级
                    cityCode = cityVO.getCityCode();
//                    BusinessRealTimePrice.getMarketList(RealTimePriceActivityNew.this, "", cityVO.getCityCode(), "", mHandler);
                    provinceCode = "";
                    countyCode = "";
                    marketCode = "";
                    minTypeCode = "";
                    onRefresh();
                }
            }
        }
    }

    /**
     * 根据关键字 搜索
     *
     * @param keyWord
     */
    private void searchData(String keyWord) {
        dataMallTvSearch.setText(keyWord);
        page = 1;
        BusinessDataMall.datamartlistcontent(this, String.valueOf(page), String.valueOf(limit), keyWord, "", mHandler);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (drawerlayout.isDrawerVisible(GravityCompat.START)) {
                drawerlayout.closeDrawer(GravityCompat.START);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
